"""
@author: Zhang Wenzhou
@file: userinfo.py
@time: 2023/3/4 0004 15:19:20
"""

from model import db
from werkzeug.security import generate_password_hash

class User(db.Model):
    __tablename__ = "userdb"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(128), nullable=False)
    _password = db.Column("password", db.String(128), nullable=False)
    role = db.Column(db.Integer, default=0)
    email = db.Column(db.String(128), nullable=False)
    # add_time      notice

    def keys(self):
        return ( 'id', 'username', 'password', 'role', 'email')


    def __getitem__(self, item):
        return getattr(self, item)

    #属性包装
    #把方法当作属性一样使用
    # #定义一些属性之前做一些检测，转换
    @property  # -----> 生成 password.setter  password.deleter
    def password(self):
        return self._password
    #user.password()   ---》 print(user.password)

    #user.password = xxxx
    @password.setter
    def password(self, value):
        self._password = generate_password_hash(value)

    @classmethod
    def create_user(cls, username, password, email):
        user = cls()    # 创建实例对象
        user.username = username
        user.password = password
        user.email = email
        #user._password = generate_password_hash(value)
        #user._password = value
        db.session.add(user)
        db.session.commit()

# API授权表的模型
# 多对多的关系    中间表
app_permission = db.Table("app_permission",
                          db.Column("api_id", db.ForeignKey("api_token.id")),
                          db.Column("permission_id", db.ForeignKey("api_permission.id"))
                          )
# api_token表
# 存放的是授权密钥，以及授权id
class ApiToken(db.Model):
    __tablename__ = "api_token"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    appid = db.Column(db.String(128), nullable=False)
    secretkey = db.Column(db.String(128), nullable=False)
    # 通过中间表区闯进啊多对多的关系
    manage = db.relationship("ApiPermission", secondary=app_permission, backref="token")

# 存放的是授权的url
class ApiPermission(db.Model):
    __tablename__ = "api_permission"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    url = db.Column(db.String(128), nullable=False)
    method_type = db.Column(db.String(128), nullable=False)
